-- NotFoundBuilding
-- Created by chendh Dec/23/2016
-- 不存在指定建筑时可点击的建筑

-- 初始化
function initNotFoundBuilding(self)
    local class = self.gridData.class;
    local buildingInfo = BuildingBonusM.queryBuildingView(class);

    if not buildingInfo then
        error("获取不到建筑查看配置，元素类型：" .. class);
        return;
    end

    -- 建筑图标
    local iconPath = getLevelItemIconPath(buildingInfo["icon"]);
    local offsetY = tonumber(buildingInfo["icon_offset_y"]);
    self.icon = ccui.ImageView:create(iconPath);
    self.icon:setTouchEnabled(true);
    self.icon:setPositionY(self.icon:getPositionY() + offsetY);
    self.item:addChild(self.icon);
    self.iconPath = iconPath;

    if self.gridData.need_shining == 1 then
        -- 闪光
        self.shiningAjustPos = cc.p(70, 100);
        shiningEffect(self.icon, self.shiningAjustPos.x, self.shiningAjustPos.y);
    end

    if self.gridData.need_animation == 1 then
        -- 呼吸
        self:doModelBreath(self.icon);
    end

    local function okFunc()
        local args = DungeonM.queryElement(self.gridData.element, "args");
        local cost = args["cost"];
        if cost then
            if cost[1] == 1 then
                if ItemM.getAmount(ME.user, cost[2]) < cost[3] then
                    alert(string.format(getLocStr("something_not_enough"), ItemM.query(cost[2],"name")));
                    return;
                end
            elseif cost[1] == 2 then
                if ME.user:queryAttrib(cost[2]) < cost[3] then
                    alert(string.format(getLocStr("something_not_enough"), FieldsM.query(cost[2],"name")));
                    return;
                end
            end
        end

        local pos = self.gridData:getPos();

        -- 奖励
        DungeonActionM.go("do_building_bonus", pos);

        if self.gridData.need_shining then
            self.icon:removeAllChildren();
        end
    end

    local function onClicked(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            if self.gridData.state == GRID_STATE_DISABLE then
                -- 已经失效，不处理
                return;
            end

            -- 打开建筑查看界面
            local notFoundBuilding = self.gridData.not_found_building;

            local isFound = false;
            for i=1, GRID_SIZE do
                local grid = DungeonM.getGridByPos(i);

                if grid.class == notFoundBuilding and
                    grid.state ~= GRID_STATE_DISABLE then
                    isFound = true;
                    break;
                end
            end
            if isFound then
                self:openBuildingView(nil, nil, buildingInfo["dialog2"], buildingInfo["view_text2"]);
            else
                self:openBuildingView(okFunc, nil, buildingInfo["dialog"], buildingInfo["view_text"]);
            end
        end
    end
    self.icon:addTouchEventListener(onClicked);
end
